package com.ljfresh.customer.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ljfresh.customer.erp.ERPConsts;
import com.ljfresh.customer.result.TokenResult;
import com.ljfresh.customer.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: Lucifer
 * @time: 2020/4/15-17:02
 */
@Controller
public class IndexController {

    @Resource
    private RedisUtils redisUtils;


    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String homePage() throws Exception{
        Object obj = redisUtils.get(ERPConsts.erpTokenRedisKey);
        TokenResult tokenResult = null;
        if (obj!=null){
             tokenResult = JSONObject.parseObject(obj.toString(), TokenResult.class);
        }
        if (tokenResult!=null){
            return "index";
        }
        String url = ERPConsts.get_code_url.replace("STATE", "0")
                .replace("APPID",ERPConsts.countAppId)
                .replace("REDIRECTURI",ERPConsts.rediRecturi);
        String cookie = "JSESSIONID=D11F29FF4848FF17F93C1C927C4EB6BA";
        URL realUrl = new URL(url);
        URLConnection connection = realUrl.openConnection();
        connection.setRequestProperty("Cookie",cookie);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(15000);
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

        // 建立实际的连接
        connection.connect();
        Map<String, List<String>> map = connection.getHeaderFields();
        List<String> strList = map.get("Location");
        String str = strList.get(0);
        System.out.println(str);
        return new String("redirect:"+url);
    }


    @GetMapping("/redirectCode")
    @ApiOperation("CODE回调")
    public String redirectCode(HttpServletRequest request,
                             @RequestParam("code")String code,
                             @RequestParam("status")String state
    ) throws Exception{
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(ERPConsts.getTokenUrl);
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("grant_type","authorization_code"));
        pairs.add(new BasicNameValuePair("code",code));
        pairs.add(new BasicNameValuePair("redirect_uri",ERPConsts.rediRecturi));
        post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
        post.addHeader("Authorization", ERPConsts.getHeader());
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");
        String responseContent = null; // 响应内容
        CloseableHttpResponse response = null;
        try {
            response = client.execute(post);
            System.out.println(JSON.toJSONString(response));
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                responseContent = EntityUtils.toString(entity, "UTF-8");
                TokenResult tokenResult = JSONObject.parseObject(responseContent, TokenResult.class);
                System.out.println("tokenResult:"+tokenResult.toString());
                redisUtils.set(ERPConsts.erpTokenRedisKey,tokenResult);
            }
            if (response != null)
                response.close();
            if (client != null)
                client.close();
        } catch(ClientProtocolException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }
        return "index";
    }
}
